import { useFlowStore } from '../stores/flowStore';
import { useState, useRef,useEffect,useCallback } from 'react';
import "./RunButton.css";

export const RunButton = () => {
  const { nodes, connections, setNodeStatus } = useFlowStore();
  const [isLooping, setIsLooping] = useState(false);
  const [loopCount, setLoopCount] = useState(0);
  const loopRef = useRef({
    running: false,
    timer: null as NodeJS.Timeout | null
  });

  const topologicalSort = (nodes: FlowNode[], connections: FlowConnection[]) => {
    const nodeMap = new Map(nodes.map(n => [n.id, n]));
    const adjList = new Map<string, string[]>();
    const inDegree = new Map<string, number>();
    
    // 初始化数据结构
    nodes.forEach(n => {
      adjList.set(n.id, []);
      inDegree.set(n.id, 0);
    });
    
    // 构建依赖图
    connections.forEach(conn => {
      adjList.get(conn.sourceId)!.push(conn.targetId);
      inDegree.set(conn.targetId, inDegree.get(conn.targetId)! + 1);
    });
    
    // 拓扑排序
    const queue = Array.from(inDegree.entries())
      .filter(([_, deg]) => deg === 0)
      .map(([id]) => id);
    
    const sorted: FlowNode[] = [];
    while (queue.length > 0) {
      const currentId = queue.shift()!;
      const node = nodeMap.get(currentId)!;
      sorted.push(node);
      
      adjList.get(currentId)!.forEach(targetId => {
        inDegree.set(targetId, inDegree.get(targetId)! - 1);
        if (inDegree.get(targetId) === 0) {
          queue.push(targetId);
        }
      });
    }
    
    return sorted;
  };

  const runFlow = async () => {
    const { nodes, connections, clearRuntimeData, functions  } = useFlowStore.getState();

    // 清除之前的运行时数据
    clearRuntimeData();
    
    // 重置所有节点状态
    nodes.forEach(n => useFlowStore.setState(state => ({
      nodes: state.nodes.map(node => 
        node.id === n.id ? { ...node, status: 'idle' } : node
      )
    })));
    
    const sortedNodes = topologicalSort(nodes, connections);
    
    for (const node of sortedNodes) {
      try {
        setNodeStatus(node.id, 'running');
        
        // 找到对应的函数定义
        const funcDef = functions.find(f => f.id === node.functionId);
        if (!funcDef) throw new Error(`Function ${node.functionId} not found`);
        
        // 执行函数并传入参数
        const result = await funcDef.execute(node.parameters);
        
        // 更新节点状态和输出
        useFlowStore.setState(state => ({
          nodes: state.nodes.map(n => 
            n.id === node.id 
              ? { ...n, status: 'success', outputs: result } 
              : n
          )
        }));
        
      } catch (error) {
        useFlowStore.getState().setNodeStatus(node.id, 'error');
        console.error(`节点执行失败: ${node.functionId}`, error);
      }
    }
  };
  // 重置节点状态
  const resetAllNodes = useCallback(() => {
    nodes.forEach(node => setNodeStatus(node.id, 'idle'));
  }, [nodes, setNodeStatus]);

  // 循环执行
  const executeLoop = useCallback(async () => {
    if (!loopRef.current.running) return;
    
    await runFlow();
    resetAllNodes();
    
    if (loopRef.current.running) {
      setLoopCount(prev => prev + 1); // 每次循环完成时增加计数
      loopRef.current.timer = setTimeout(executeLoop, 2000);
    }
  }, [resetAllNodes]);


  // 启动/停止循环
  const toggleLoop = useCallback(() => {
    const shouldRun = !loopRef.current.running;
    loopRef.current.running = shouldRun;
    setIsLooping(shouldRun);
    
    if (shouldRun) {
      setLoopCount(0);
      resetAllNodes();
      executeLoop();
    } else {
      // 清除定时器
      if (loopRef.current.timer) {
        clearTimeout(loopRef.current.timer);
        loopRef.current.timer = null;
      }
    }
  }, [executeLoop, resetAllNodes]);

  // 组件卸载时停止循环
  useEffect(() => {
    return () => {
      // 安全访问current
      if (loopRef.current) {
        loopRef.current.running = false;
        if (loopRef.current.timer) {
          clearTimeout(loopRef.current.timer);
        }
      }
    };
  }, []);


  return (
    <div className="run-controls">
      {/* 原有单次运行按钮（保持不变） */}
      <button onClick={runFlow}
        style={{ background: '#1890ff' }}
      >单次运行</button>
      
      {/* 新增循环按钮 */}
      <button 
        onClick={toggleLoop}
        style={{ background: isLooping ? '#ff4d4f' : '#1890ff' }}
      >
        {isLooping ? `停止循环 (已${loopCount}次)` : '循环运行'} {/* 显示计数 */}
      </button>
    </div>
  );
};